import os
import re
import sys
import time
from pathlib import Path
import markdownify
from tqdm import tqdm
import html2text
from load_filter_config import load_filter_config
from get_solution import get_solution
#request_config
def merged_html(hhc_path,output_path,file_list_path,image_prefix_config,filter_image=True,image_filter_config=None):
    os.chdir(Path(hhc_path).parent)
    path_object = Path(hhc_path)
    path_prefix = str(path_object.resolve()).replace(str(path_object.name),"")
    path_prefix = path_prefix.replace("\\","/")
    file_list_object = open(file_list_path + "\\" + "filelist.txt", "w", encoding='utf-8')#导出文件列表生成
    file = open(hhc_path,"r",encoding='gbk')#hhc -- chm 文件列表
    content = file.read()
    compiled_li = re.compile('<LI><OBJECT type="text/sitemap">(.+?)</OBJECT>',re.S)
    result_list = compiled_li.findall(content)
    bar = tqdm(total=len(result_list),desc="convert")

    if filter_image == False:
        solution_config_list , image_list = load_filter_config(image_filter_config['excel_path'])




    for file_output_index,per_object in enumerate(result_list[0:]):
        compiled_file_name = re.compile(r'<param name="Name" value="(.+)">')
        file_name = compiled_file_name.search(per_object).group(1)

        compiled_html_path = re.compile(r'<param name="Local" value="(.+)"')
        html_path  = path_prefix + compiled_html_path.search(per_object).group(1)
        # print()
        pattern = r'[\\/:*?"<>|\r\n&;]+'
        file_name = re.sub(pattern,"_",file_name)
        html_file = open(html_path,"r",encoding='gbk')
        html_content = html_file.read()

        # print(html_content)

        # markdown_text = markdownify.markdownify(html_content)
        markdown_text = html2text.html2text(html_content)
        #
        if filter_image == True:
            image_link_compiled = re.compile(r"!\[.*?\]\((.+)\)")#去图片引用
            markdown_text = image_link_compiled.sub("",markdown_text)
        else:
            image_link_compiled = re.compile(r"!\[(.*?)\]\((.+?)\)")
            markdown_text =  image_link_compiled.sub(r"!【\1】(\2)" ,markdown_text)



        link_compiled_text_compiled = re.compile(r"\[(.+?)\]\(.+?\.html.*\)")  #摘[]内的字
        markdown_text = link_compiled_text_compiled.sub(r"\1",markdown_text)



        if filter_image == False:
            image_link_compiled = re.compile(r"!【(.*?)】\((.+?)\)",re.DOTALL)
            image_link_list = image_link_compiled.findall(markdown_text)
            if len(image_link_list) != 0:
                for image_link in image_link_list:
                    try:

                        getted_text = f"!【{image_link[0]}】({image_link[1]})"  # 要替换的文本，【】image链接
                        new_text = f"![{image_link[0]}]"
                        # print(new_text)
                        image_path_object = Path(image_link[1])  # chm 图片相对链接读入
                        html_path_object = Path(html_path)  # html完整链接读入

                        os.chdir(html_path_object.parent)  # 切换到该html的父目录
                        os.chdir(image_path_object.parent)  # 进入该html的images文件夹
                        result_path = os.getcwd() + "\\" + image_path_object.name  # 完整的html image文件路径构成
                        solution_for_image = get_solution(result_path,solution_config_list,image_list)
                        if solution_for_image == None:
                            prefix_web_path = image_prefix_config['base_url'] + image_prefix_config[
                                'classify'] + "/"  # 图床前缀字符加入,http://localhost:16000/S2700_3700
                            # print(prefix_web_path)
                            result_path = result_path.replace(image_prefix_config['chm_base_path'] + "\\",
                                                              prefix_web_path)  # 将chm本地拆分后存放目录，更改为图床URL
                            result_path = result_path.replace("\\", "/")  # 彻底剔除\，转换为/
                            # print(result_path)
                            new_text = new_text + f"({result_path})"
                            # print()
                            # print(getted_text,new_text)#最终字符串形成
                            # markdown_text.index(getted_text)
                            markdown_text = markdown_text.replace(getted_text, new_text)
                        else:
                            image_method_solution = solution_for_image['method']
                            # print(image_method_solution)
                            if image_method_solution == "替换":
                                new_text = solution_for_image['value']
                                markdown_text = markdown_text.replace(getted_text, new_text)
                            elif image_method_solution == "丢弃":
                                new_text = ""
                                markdown_text = markdown_text.replace(getted_text, new_text)


                    except Exception as err:
                        image_link_compiled = re.compile(r"(!【】\((.+?\).+?)\))", re.DOTALL)
                        getted_text = image_link_compiled.search(markdown_text).group(1)
                        new_text = f"![{image_link[0]}]"
                        image_path_object = image_link_compiled.search(markdown_text).group(2)
                        image_path_object = image_path_object.replace("\\(","(").replace("\\)",")")
                        image_path_object = Path(image_path_object)
                        html_path_object = Path(html_path)
                        os.chdir(html_path_object.parent)
                        os.chdir(image_path_object.parent)

                        result_path = os.getcwd() + "\\" + image_path_object.name
                        solution_for_image = get_solution(result_path,solution_config_list,image_list)
                        if solution_for_image == None:
                            prefix_web_path = image_prefix_config['base_url'] + image_prefix_config[
                                'classify'] + "/"  # 图床前缀字符加入,http://localhost:16000/S2700_3700
                            result_path = result_path.replace(image_prefix_config['chm_base_path'] + "\\",
                                                              prefix_web_path)  # 将chm本地拆分后存放目录，更改为图床URL
                            result_path = result_path.replace("\\", "/")  # 彻底剔除\，转换为/

                            new_text = new_text + f"({result_path})"
                            # print(getted_text,new_text)#最终字符串形成
                            # markdown_text.index(getted_text)
                            markdown_text = markdown_text.replace(getted_text, new_text)
                        else:
                            image_method_solution = solution_for_image['method']
                            # print(image_method_solution)
                            if image_method_solution == "替换":
                                new_text = solution_for_image['value']
                                markdown_text = markdown_text.replace(getted_text, new_text)
                            elif image_method_solution == "丢弃":
                                new_text = ""
                                markdown_text = markdown_text.replace(getted_text, new_text)



                        #

        file_list_object.write(f"{html_path}-------{output_path}\\{file_output_index+1}.{file_name}.md\n")
        # print(f"{html_path}-------{output_path}\\{file_output_index+1}.{file_name}.md")
        markdown_file_object = open(f"{output_path}\\{file_output_index+1}.{file_name}.md","w",encoding='utf-8')
        markdown_file_object.write(markdown_text)
        markdown_file_object.close()





        html_file.close()
        bar.update()
        # bar.write(f"{html_path} -- {file_name}",file=sys.stdout,end="")

    file_list_object.close()

if __name__ == "__main__":
    hhc_path = r"G:\AI\HUAWEI\chm_split\dc_s_v1r6_Product_Doc_cn_all.hhc"
    output_path = r"G:\AI\HUAWEI\merge_out"
    file_list_path = r"G:\AI\HUAWEI" 
    image_prefix_config = {  #大模型输出图片时，文档路径转图床路径
        "chm_base_path":"G:\AI\HUAWEI\chm_split",
        # "base_url":"http://www.bluejalor.com:16000/",
        "base_url":"http://localhost:16000/",
        "classify":"S2700_3700"
    }
    image_filter_config = {  #图标替换逻辑
        'excel_path':r"G:\AI\HUAWEI\icon_replace.xlsx"
    }

    merged_html(hhc_path,output_path,file_list_path,
                image_prefix_config=image_prefix_config,
                image_filter_config = image_filter_config,
                filter_image=False)